import * as signalR from '@microsoft/signalr';

class chatHub {
  private static instance: chatHub;
  private hubConnection: signalR.HubConnection;

  private constructor(url: string, token: string) {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl(url, {
        accessTokenFactory: () => token, // 设置访问令牌
      })
      .configureLogging(signalR.LogLevel.Information)
      .build();

    this.startConnection();
  }

  public static getInstance(url: string, token: string): chatHub {
    if (!chatHub.instance) {
      chatHub.instance = new chatHub(url, token);
    }
    return chatHub.instance;
  }

  private async startConnection() {
    try {
      await this.hubConnection.start();
      console.log('Connection started');
    } catch (err) {
      console.error('Error while starting connection: ' + err);
      setTimeout(() => this.startConnection(), 5000); // Retry connection
    }
  }

  private async ensureConnection() {
    if (this.hubConnection.state !== signalR.HubConnectionState.Connected) {
      console.log('Connection is not active, attempting to reconnect...');
      await this.startConnection();
    }
  }

  public async SendNotification(message: string) {
    await this.ensureConnection();
    try {
      await this.hubConnection.invoke('SendNotification', message);
    } catch (err) {
      console.error('Error sending notification: ' + err);
    }
  }

  public async SendBiologicalMessage(message: string) {
    await this.ensureConnection();
    try {
      await this.hubConnection.invoke('SendBiologicalIssueMessage', message);
    } catch (err) {
      console.error('Error sending biological message: ' + err);
    }
  }

  public async SendChemistryAskMessage(message: string) {
    await this.ensureConnection();
    try {
      await this.hubConnection.invoke('SendChemistryAskMessage', message);
    } catch (err) {
      console.error('Error sending chemistry ask message: ' + err);
    }
  }

  public ReceiveStocknNtification(callback: (message: string) => void) {
    this.hubConnection.on('ReceiveNotification', (message: string) => {
      callback(message);
    });
  }

  public ReceiveBiologicalIssueMessage(callback: (message: string) => void) {
    this.hubConnection.on('ReceiveBiologicalIssueMessage', (message: string) => {
      callback(message);
    });
  }
  public onReceivePrivateMessage(callback: (message: string) => void) {
    this.hubConnection.on('ReceiveChemistryAnswerMessage', (message: string) => {
      callback(message);
    });
  }

  public onReceiveMessage(callback: (user: string, message: string) => void) {
    this.hubConnection.on('ReceiveMessage', (user: string, message: string) => {
      callback(user, message);
    });
  }
}

export default chatHub;
